// pages/enterprise/user/personnel-edit/index.js
import {authorizationSetting, enterpriseDelete} from "../../../service/Personnel";
import Dialog from "@vant/weapp/dialog/dialog";
import Toast from "@vant/weapp/toast/toast";
Page({

    /**
     * 页面的初始数据
     */
    data: {
        switch: {
            checked: true,
            loading: false
        },
        btnLoading: false
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {
        this.data._options = options;
        this.setData({"switch.checked": options.auth > 0})
    },

    /*
    * 监听开关状态切换
    * */
    onSwitchChange: async function(e) {
        const that = this;
        let value = e.detail;
        try {
            let loading = this.data.switch.loading;
            if (loading) return false;
            let id = this.data._options.id;
            this.setData({
                "switch.checked": value,
                "switch.loading": true
            });
            await authorizationSetting({
                id,
                auth: value ? 1 : 0
            })
            clearTimeout(that._TimeOut);
            that._TimeOut = setTimeout(function () {
                const eventChannel = that.getOpenerEventChannel();
                eventChannel.emit("acceptDataFromOpenedPage", {status: "edit"});
            }, 1500)
        } catch (e) {
            this.setData({"switch.checked": !value});
            console.error(e)
        } finally {
            this.setData({"switch.loading": false})
        }
    },

    /*
    * 删除按钮监听
    * */
    onDeleteButton: async function () {
        try {
            const that = this;
            let id = this.data._options.id;
            let btnLoading = this.data.btnLoading;
            if (btnLoading) return false;
            this.setData({btnLoading: true});
            await Dialog.confirm({
                title: "删除提示",
                message: "确认删除该员工管理信息?",
            });
            await enterpriseDelete(id);
            Toast({type: "success", message: "删除成功！"});
            clearTimeout(that._TimeOut);
            that._TimeOut = setTimeout(function () {
                const eventChannel = that.getOpenerEventChannel();
                eventChannel.emit("acceptDataFromOpenedPage", {status: "delete"});
                wx.navigateBack();
            }, 1500)
        } catch (e) {
            console.log(e)
        } finally {
            this.setData({btnLoading: false});
        }
    }
})